package com.ewing.extranal.im.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ewing.extranal.im.dto.ImRelationInfo;

/**
 * 
 * 
 * @author tansonlam
 * @createDate 2016年5月3日
 * 
 */
public class ImRelationImpl implements ImRelation {

    private final static Map<Long, List<ImRelationInfo>> relationTable = new HashMap<>();

    @Override
    public ImRelationInfo addRelation(Long imUserId, Long relImUserId) {
        List<ImRelationInfo> relationList = relationTable.get(imUserId);
        if (relationList == null) {
            relationList = new ArrayList<>();
            relationTable.put(imUserId, relationList);
        }

        for (ImRelationInfo relation : relationList) {
            if (relation.getUserInfo().getImUserId().equals(relImUserId)) {
                return relation;
            }
        }
        ImUser imUser = new ImUserImpl();
        ImRelationInfo imRelationInfo = new ImRelationInfo(imUser.getUserInfo(relImUserId));
        relationList.add(imRelationInfo);
        if (relationList.size() == 2)
            System.out.println(111);
        return imRelationInfo;
    }

    @Override
    public List<ImRelationInfo> getRelation(Long imUserId) {
        return relationTable.get(imUserId);
    }

    @Override
    public Boolean removeRelation(Long imUserId, Long relImUserId) {
        List<ImRelationInfo> relationList = relationTable.get(imUserId);
        if (relationList == null) {
            return false;
        }
        List<ImRelationInfo> cloneList = new ArrayList<>();
        cloneList.addAll(relationList);
        for (ImRelationInfo imRelationInfo : cloneList) {
            if (imRelationInfo.getUserInfo().getImUserId().equals(relImUserId)) {
                relationList.remove(imRelationInfo);
            }
        }
        return true;
    }

    @Override
    public String getRelationIdOrCreate(Long imUserId, Long relImUserId) {
        List<ImRelationInfo> relationList = relationTable.get(imUserId);
        if (relationList == null) {
            relationList = new ArrayList<>();
            relationTable.put(imUserId, relationList);
        }

        for (ImRelationInfo relation : relationList) {
            if (relation.getUserInfo().getImUserId().equals(relImUserId)) {
                return relation.getRelationId();
            }
        }

        return addRelation(imUserId, relImUserId).getRelationId();
    }

    @Override
    public Boolean existRelation(Long imUserId, Long relImUserId) {
        List<ImRelationInfo> relationList = relationTable.get(imUserId);
        if (relationList == null)
            return false;

        for (ImRelationInfo relation : relationList) {
            if (relation.getUserInfo().getImUserId().equals(relImUserId)) {
                return true;
            }
        }
        return false;
    }
}
